package com.hp.jdoss.config;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.util.IOUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

/**
 * JdossTemplate
 *
 * @author dongxing
 */
@AllArgsConstructor
public class JdossTemplate {

   private OssProperties ossProperties;
   private AmazonS3 amazonS3;

   /**
    * 创建存储空间
    *
    * @param bucketName
    */
   @SneakyThrows
   public void makeBucket(String bucketName) {
      if (!bucketExists(bucketName)) {
         amazonS3.createBucket(bucketName);
      }
   }


   /**
    * 判断存储空间是不是存在
    *
    * @param bucketName
    * @return
    */
   @SneakyThrows
   public boolean bucketExists(String bucketName) {
      List<Bucket> buckets = amazonS3.listBuckets();
      for (Bucket bucket : buckets) {
         if (bucket.getName().equals(bucketName)) {
            return true;
         }
      }
      return false;
   }

   /**
    * 存储文件
    *
    * @param file
    * @return
    */
   @SneakyThrows
   public Map<String, String> putFile(MultipartFile file) {
      return put(ossProperties.getBucketName(), file.getOriginalFilename(), file.getInputStream());
   }

   @SneakyThrows
   public Map<String, String> put(String bucketName, String fileName, InputStream stream) {
      makeBucket(bucketName);
      fileName = getFileName(fileName);
      //上传这里的 objectMetadata.setContentLength 必须设置，否则报错，直接设置文件流的length也报错，京东官方没有说明，具体原因百度
      byte[] bytes = IOUtils.toByteArray(stream);
      ObjectMetadata objectMetadata = new ObjectMetadata();
      objectMetadata.setContentLength(bytes.length);
      objectMetadata.setContentType("application/octet-stream");
      ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
      // 上传
      amazonS3.putObject(bucketName, fileName, byteArrayInputStream, objectMetadata);
      Map<String, String> rMap = new HashMap<>(2);
      rMap.put("fileName",fileName);
      rMap.put("url",ossProperties.getEndpoint().concat(StringPool.SLASH).concat(bucketName).concat(StringPool.SLASH).concat(fileName));
      return rMap;
   }

   /**
    * 根据规则生成文件名称规则
    *
    * @param originalFilename 原始文件名
    * @return string
    */
   private String getFileName(String originalFilename) {
      return getUUID() + StringPool.DOT + originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
   }

   private String getUUID() {
      ThreadLocalRandom random = ThreadLocalRandom.current();
      return new UUID(random.nextLong(), random.nextLong()).toString().replace(StringPool.DASH, StringPool.EMPTY);
   }
}
